<?php

namespace app\admin\controller;

use app\admin\common\Base;
use think\Db;
use think\Session;

use app\admin\model\Goods as Model;
use app\admin\model\GoodsPriceStrategy as PriceStrategyModel;
use app\admin\model\GoodsStockWarning as StockWarningModel;
use app\admin\model\GoodsBeginSetting as BeginSettingModel;

class Goods extends Base
{
    public function index()
    {
        $data = $this->request->param();

        if (isset($data['ajax']) && $data['ajax'] == 100) {
            $map = '';
            $page = isset($data['page']) ? $data['page'] : 1;
            $page = intval($page);
            $limit = isset($data['rows']) ? $data['rows'] : 10;
            $limit = intval($limit);
            $start = $limit * ($page - 1);

            //搜索
            if(isset($data['search'])){

                $sql = db('goods')->where(['is_del' => 0 , 'enterprise_id' => $this->EnterpriseId]);
                $sql = empty($data['matchCon']) ? $sql : $sql->where('sn|name|code|model' , 'like' , '%' . $data['matchCon'] . '%');
                $sql = empty($data['state_type_name']) ? $sql : $sql->where('status',$data['state_type_name']);
                $list = $sql->select();

            }else{

                if (isset($data['goods_category']) && $data['goods_category'] != 0) {
                    $list = Db::name('goods')->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->where('goods_category_id', $data['goods_category'])->order('id asc')->limit($start, $limit)->select();
                    $count = Db::name('goods')->where('enterprise_id', $this->EnterpriseId)->where('is_del', 0)->where('goods_category_id', $data['goods_category'])->count();
                } else {
                    $list = Db::name('goods')->where('is_del', 0)->order('id asc')->where('enterprise_id', $this->EnterpriseId)->limit($start, $limit)->select();
                    $count = Db::name('goods')->where('enterprise_id', $this->EnterpriseId)->where('is_del', 0)->count();
                }

                foreach ($list as $key => $value) {
                    $list[$key]['category_name'] = Db::name('goods_category')->where('id', $value['goods_category_id'])->where('is_del', 0)->value('name');
                    $list[$key]['store_name'] = Db::name('store')->where('id', $value['store_id'])->where('is_del', 0)->value('name');
                    $list[$key]['stock_num'] = get_stock($value['store_id'], $value['id']);

                    $begin_setting = Db::name('goods_begin_setting')->where('goods_id', $value['id'])->where('is_del', 0)->find();
                    if ($begin_setting) {
                        $list[$key]['begin_num'] = $begin_setting['begin_num'];
                        $list[$key]['cost_price'] = $begin_setting['cost_price'];
                        $list[$key]['cost_price'] = $begin_setting['cost_price'];
                        $list[$key]['begin_total_price'] = $begin_setting['begin_total_price'];
                    }

                    $price_strategy = Db::name('goods_price_strategy')->where('goods_id', $value['id'])->where('is_del', 0)->find();
                    if ($price_strategy) {
                        $list[$key]['estimated_purchase_price'] = $price_strategy['estimated_purchase_price'];
                        $list[$key]['sale_price'] = $price_strategy['sale_price'];
                        $list[$key]['batch_price'] = $price_strategy['batch_price'];
                        $list[$key]['vip_price'] = $price_strategy['vip_price'];
                    }
                    $list[$key]['img_path'] = Db::name('upload_img')->where('id', $value['main_img_id'])->value('path');
                }
            }
            return $this->grid_data($list, $count, $page, $limit);
        }
        return $this->fetch();
    }

    public function add()
    {
        $store = Db::name('store')->where('status', 0)->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->select();
        $unit = Db::name('unit')->where('pid', -1)->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->select();
        $multi_unit = get_multi_unit();

        $this->assign('store', $store);
        $this->assign('unit', $unit);
        $this->assign('multi_unit', $multi_unit);
        $this->assign('store_ew', json_encode($store));
        return $this->fetch();
    }

    // 编辑栏目1-1
    public function edit($id)
    {
        $info = Db::name('goods')->where('id', $id)->find();

        $info['store_name'] = Db::name('store')->where('id', $info['store_id'])->value('name');
        $info['unit_name'] = Db::name('unit')->where('id', $info['unit'])->value('name');
        $info['first_out_unit_name'] = Db::name('unit')->where('id', $info['first_out_unit'])->value('name');
        $info['first_in_unit_name'] = Db::name('unit')->where('id', $info['first_in_unit'])->value('name');
        $info['multi_unit_name'] = one_multi_unit($info['multi_unit']);
        $info['goods_category_name'] = Db::name('goods_category')->where('id', $info['goods_category_id'])->value('name');
        // 多单位数据
        if ($info['is_multi_unit'] == 1) {
            $price_strategy = Db::name('goods_price_strategy')->where('goods_id', $info['id'])->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->select();
            foreach ($price_strategy as $key => $value) {
                $price_strategy[$key]['name'] = Db::name('unit')->where('id', $value['unit_id'])->value('name');
            }
            $info['price_strategy'] = json_encode($price_strategy);
        }

        // 库存预警
        if ($info['is_stock_warning'] == 1) {
            $stock_warning = Db::name('goods_stock_warning')->where('goods_id', $info['id'])->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->select();
            foreach ($stock_warning as $key => $value) {
                $stock_warning[$key]['cangku'] = Db::name('store')->where('id', $value['store_id'])->value('name');
            }
            $info['stock_warning'] = json_encode($stock_warning);
        }

        // 初期设置
        if ($info['is_begin_setting'] == 1) {
            $begin_setting = Db::name('goods_begin_setting')->where('goods_id', $info['id'])->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->select();
            foreach ($begin_setting as $key => $value) {
                $begin_setting[$key]['store_name'] = Db::name('store')->where('id', $value['store_id'])->value('name');
            }
            $info['begin_setting'] = json_encode($begin_setting);
        }

        // 图片
        $info['imgsList'] = Db::name('upload_img')->where('pid', $info['id'])->where('is_del', 0)->select();
        $info['imgsnum'] = count($info['imgsList']);
        // halt($info);

        $store = Db::name('store')->where('status', 0)->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->select();
        $unit = Db::name('unit')->where('pid', -1)->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->select();
        $multi_unit = get_multi_unit();

        $this->assign('store', $store);
        $this->assign('unit', $unit);
        $this->assign('multi_unit', $multi_unit);
        $this->assign('store_ew', json_encode($store));

        $this->assign('info', $info);
        return $this->fetch();
    }

    // 复制栏目1-1
    public function copy($id)
    {
        $info = Db::name('goods')->where('id', $id)->find();

        $info['store_name'] = Db::name('store')->where('id', $info['store_id'])->value('name');
        $info['unit_name'] = Db::name('unit')->where('id', $info['unit'])->value('name');
        $info['first_out_unit_name'] = Db::name('unit')->where('id', $info['first_out_unit'])->value('name');
        $info['first_in_unit_name'] = Db::name('unit')->where('id', $info['first_in_unit'])->value('name');
        $info['multi_unit_name'] = one_multi_unit($info['multi_unit']);
        $info['goods_category_name'] = Db::name('goods_category')->where('id', $info['goods_category_id'])->value('name');
        // 多单位数据
        if ($info['is_multi_unit'] == 1) {
            $price_strategy = Db::name('goods_price_strategy')->where('goods_id', $info['id'])->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->select();
            foreach ($price_strategy as $key => $value) {
                $price_strategy[$key]['name'] = Db::name('unit')->where('id', $value['unit_id'])->value('name');
            }
            $info['price_strategy'] = json_encode($price_strategy);
        }

        // 库存预警
        if ($info['is_stock_warning'] == 1) {
            $stock_warning = Db::name('goods_stock_warning')->where('goods_id', $info['id'])->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->select();
            foreach ($stock_warning as $key => $value) {
                $stock_warning[$key]['cangku'] = Db::name('store')->where('id', $value['store_id'])->value('name');
            }
            $info['stock_warning'] = json_encode($stock_warning);
        }

        // 初期设置
        if ($info['is_begin_setting'] == 1) {
            $begin_setting = Db::name('goods_begin_setting')->where('goods_id', $info['id'])->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->select();
            foreach ($begin_setting as $key => $value) {
                $begin_setting[$key]['store_name'] = Db::name('store')->where('id', $value['store_id'])->value('name');
            }
            $info['begin_setting'] = json_encode($begin_setting);
        }

        // 图片
        $info['imgsList'] = Db::name('upload_img')->where('pid', $info['id'])->where('is_del', 0)->select();
        $info['imgsnum'] = count($info['imgsList']);
        // halt($info);

        $store = Db::name('store')->where('status', 0)->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->select();
        $unit = Db::name('unit')->where('pid', -1)->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->select();
        $multi_unit = get_multi_unit();

        $this->assign('store', $store);
        $this->assign('unit', $unit);
        $this->assign('multi_unit', $multi_unit);
        $this->assign('store_ew', json_encode($store));

        $this->assign('info', $info);
        return $this->fetch();
    }

    // 编辑保存
    public function update()
    {
        $data = $this->request->param();
        // 多单位
        if ($data['is_multi_unit'] == '1') {
            $goods_price_strategy = $data['price_strategy'];
            unset($data['price_strategy']);
        }

        // 库存预警
        if ($data['is_stock_warning'] == '1') {
            $goods_stock_warning = $data['stock_warning'];
            unset($data['stock_warning']);
        }

        // 初期设置
        if ($data['is_begin_setting'] == '1') {
            $goods_begin_setting = $data['begin_setting'];
            unset($data['begin_setting']);
        }

        // 主图图片
        if (!empty($data['imgsList'])) {
            $data['main_img_id'] = $data['imgsList'][0];
        }
        $data['enterprise_id'] = $this->EnterpriseId;
        $data['updatetime'] = time();
        $model = new Model();
        Db::startTrans();
        $result = $model->allowField(true)->save($data, ['id' => $data['id']]);
        $goods_id = $model->id;
        if (!$result) {
            Db::rollback();
            return json(['status' => 1, 'msg' => '操作失败1']);
        }

        // 多单位
        if ($data['is_multi_unit'] == '1') {
            foreach ($goods_price_strategy as $key => $value) {
                $goods_price_strategy[$key]['goods_id'] = $goods_id;
                $goods_price_strategy[$key]['enterprise_id'] = $this->EnterpriseId;
                $goods_price_strategy[$key]['updatetime'] = time();
            }
            $price_strategy = new PriceStrategyModel;
            $res = $price_strategy->allowField(true)->saveAll($goods_price_strategy);
            if (!$res) {
                Db::rollback();
                return json(['status' => 1, 'msg' => '操作失败2']);
            }
        }

        // 图片
        if (!empty($data['imgsList'])) {
            foreach ($data['imgsList'] as $key => $value) {
                $res = Db::name('upload_img')->where('id', $value)->update(['pid' => $goods_id, 'updatetime' => time()]);
                if (!$res) {
                    Db::rollback();
                    return json(['status' => 1, 'msg' => '操作失败3']);
                }
            }
        }

        // 库存预警
        if ($data['is_stock_warning'] == '1') {
            foreach ($goods_stock_warning as $key => $value) {
                $goods_stock_warning[$key]['goods_id'] = $goods_id;
                $goods_stock_warning[$key]['enterprise_id'] = $this->EnterpriseId;
                $goods_stock_warning[$key]['updatetime'] = time();
            }
            $stock_warning = new StockWarningModel;
            $res = $stock_warning->allowField(true)->saveAll($goods_stock_warning);
            if (!$res) {
                Db::rollback();
                return json(['status' => 1, 'msg' => '操作失败4']);
            }
        }

        // 初期设置
        if ($data['is_begin_setting'] == '1') {
            foreach ($goods_begin_setting as $key => $value) {
                $goods_begin_setting[$key]['goods_id'] = $goods_id;
                $goods_begin_setting[$key]['enterprise_id'] = $this->EnterpriseId;
                $goods_begin_setting[$key]['updatetime'] = time();
            }
            $begin_setting = new BeginSettingModel;
            $res = $begin_setting->allowField(true)->saveAll($goods_begin_setting);
            if (!$res) {
                Db::rollback();
                return json(['status' => 1, 'msg' => '操作失败5']);
            }
        }

        Db::commit();
        return json(['status' => 1, 'msg' => '更新成功']);
    }

    //编辑栏目1-2
    public function save()
    {
        $data = $this->request->param();

        if (empty($data['id'])) {
            // 多单位
            if ($data['is_multi_unit'] == '1') {
                $goods_price_strategy = $data['price_strategy'];
                unset($data['price_strategy']);
            }

            // 库存预警
            if ($data['is_stock_warning'] == '1') {
                $goods_stock_warning = $data['stock_warning'];
                unset($data['stock_warning']);
            }

            // 初期设置
            if ($data['is_begin_setting'] == '1') {
                $goods_begin_setting = $data['begin_setting'];
                unset($data['begin_setting']);
            }

            // 主图图片
            if (!empty($data['imgsList'])) {
                $data['main_img_id'] = $data['imgsList'][0];
            }
            $data['enterprise_id'] = $this->EnterpriseId;
            $model = new Model();
            Db::startTrans();
            $result = $model->allowField(true)->save($data);
            $goods_id = $model->id;
            if (!$result) {
                Db::rollback();
                return json(['status' => 1, 'msg' => '操作失败']);
            }

            // 多单位
            if ($data['is_multi_unit'] == '1') {
                foreach ($goods_price_strategy as $key => $value) {
                    $goods_price_strategy[$key]['goods_id'] = $goods_id;
                    $goods_price_strategy[$key]['enterprise_id'] = $this->EnterpriseId;
                }
                $price_strategy = new PriceStrategyModel;
                $res = $price_strategy->allowField(true)->saveAll($goods_price_strategy);
                if (!$res) {
                    Db::rollback();
                    return json(['status' => 1, 'msg' => '操作失败']);
                }
            }

            // 图片
            if (!empty($data['imgsList'])) {
                foreach ($data['imgsList'] as $key => $value) {
                    $res = Db::name('upload_img')->where('id', $value)->update(['pid' => $goods_id]);
                    if (!$res) {
                        Db::rollback();
                        return json(['status' => 1, 'msg' => '操作失败']);
                    }
                }
            }

            // 库存预警
            if ($data['is_stock_warning'] == '1') {
                foreach ($goods_stock_warning as $key => $value) {
                    $goods_stock_warning[$key]['goods_id'] = $goods_id;
                    $goods_stock_warning[$key]['enterprise_id'] = $this->EnterpriseId;
                }
                $stock_warning = new StockWarningModel;
                $res = $stock_warning->allowField(true)->saveAll($goods_stock_warning);
                if (!$res) {
                    Db::rollback();
                    return json(['status' => 1, 'msg' => '操作失败']);
                }
            }

            // 初期设置
            if ($data['is_begin_setting'] == '1') {
                foreach ($goods_begin_setting as $key => $value) {
                    $goods_begin_setting[$key]['goods_id'] = $goods_id;
                    $goods_begin_setting[$key]['enterprise_id'] = $this->EnterpriseId;
                }
                $begin_setting = new BeginSettingModel;
                $res = $begin_setting->allowField(true)->saveAll($goods_begin_setting);
                if (!$res) {
                    Db::rollback();
                    return json(['status' => 1, 'msg' => '操作失败']);
                }
            }

            Db::commit();
            $status = 1;
            $msg = "添加成功";
        } else {
            $id = $data['id'];
            $model = new Model();
            $result = $model->allowField(true)->save($data, ["id" => $id]);
            if ($result) {
                $status = 1;
                $msg = "更新成功";
            }
        }
        return json(['status' => $status, 'msg' => $msg]);
    }

    //删除栏目1-1
    public function del($id)
    {   

            $status = 0;
            $msg = "操作失败";
            $del = Db::name('goods')->where('id', $id)->update(["is_del" => 1]);
            if ($del) {
                $status = 1;
                $msg = "删除成功";
            }

        
        return ['status' => $status, 'msg' => $msg];
    }
    //多选禁用启用
    public function disable()
    {
        $data = $this->request->param();

        if ($data['id'] == 0) {//0是启用 1是禁用  

            $disable = db('goods')
                        ->where(['is_del' => 0,'enterprise_id' => $this->EnterpriseId])
                        ->where('id','in',$data['ids'])
                        ->setField('status',$data['id']);
            if ($disable) {
                return json(['code' => 1 , 'msg' => '启用成功']);
            }else{
                return json(['code' => 1 , 'msg' => '启用失败']);
            }

        }else{

            $disable = db('goods')
                        ->where(['is_del' => 0,'enterprise_id' => $this->EnterpriseId])
                        ->where('id','in',$data['ids'])
                        ->setField('status',$data['id']);
            if ($disable) {
                return json(['code' => 1 , 'msg' => '禁用成功']);
            }else{
                return json(['code' => 1 , 'msg' => '禁用失败']);
            }

        }

    }
    public function delss()
    {
        $data = $this->request->param();

        $status = 0;
        $msg = "操作失败";
        $del = db('goods')->where('id','in',$data['ids'])->setField('is_del',1); 

        if ($del) {
            $status = 1;
            $msg = "删除成功";
        }

        return ['status' => $status, 'msg' => $msg];
    }
}
